package com.able.concurrency.t2;

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author abel.he
 * @data 2018/8/18 14:34
 * @describe
 */
public class Test5_1<E> {

    private LinkedList<E> linkedList = new LinkedList<E>();

    private final int MAX = 10;

    private AtomicInteger count = new AtomicInteger(0);

    synchronized AtomicInteger count() {return this.count;}

    synchronized void put(E e ) {
        while (linkedList.size() == MAX) {
            try {
                this.wait();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }

        linkedList.add(e);
        count.incrementAndGet();
        this.notifyAll();
    }

    synchronized E get() {
        while (linkedList.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        E result = linkedList.removeFirst();
        count.decrementAndGet();
        this.notifyAll();
        return result;
    }

    public static void main(String[] args) {
        final Test5_1 test51 = new Test5_1();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    for (int j = 0; j < 5; j++) {
                        System.out.println(Thread.currentThread().getName() + " 获取数据：" + test51.get() + " 现有数据量： " + test51.count());
                    }
                }
            }, "consumer" + i).start();
        }

        for (int i = 0; i < 2; i++) {
             new Thread(new Runnable() {
                public void run() {
                    for (int j = 0; j < 25; j++) {
                        test51.put(Thread.currentThread().getName() + " - " + j);
                    }
                }
            }, "producer " + i).start();
        }
    }

}
